(function($){
	$.fn.tabPanel = function(options){
		var settings = $.extend({
			paneWidth:"100%",
			paneHeight:"100px",
			setContentDroppable:{
				accepts:".setObject",
				revert:true,
				greedy:true,
				drop:function(e,ui){
					if(
						$(ui.helper).find(".form-tabbable-pane").length >= 1
						//$(ui.helper).find(".form-table").length >= 1
					){
						//do nothing
					}else{
						//evtarget = (window.event) ? window.event.srcElement /* for IE */ : e.target;
				        //console.log(ui)
				        //console.log(e.target)
				        //console.log(ui.draggable[0].parentElement);
				        var target = e.target;
				        var source = ui.draggable[0].parentElement;
				        if(target === source){ //conditional purpose to prevent dropping off the same place
				            //alert('Same droppable container');
				    	}else{
				    		$(ui.helper).appendTo(this);
				    		if($(ui.helper).hasClass("ui-draggable")){
				    			$(ui.helper).draggable("option","containment","parent");
				    		}
							$(ui.helper).css({
								"top":"0px",
								"left":"0px"
							});
				    	}
					}
				}
			},
			resizableContent:false,
			resizableContentContainment:null,
		},options);
		console.log(settings.setContentDroppable)
		return this.each(function(eqi_tabPanel){
			if($(this).closest(".tab-panel-parent-container").length == 0){
				$(this).wrap("<div class='tab-panel-parent-container' style='position:relative;'/>");
			}else{
				
			}
			
			if($(this).find(">ul").length >= 1){
				if($(this).find(">ul").find(">li.li-add-new-tab-panel").length == 0){
					$(this).find(">ul").append(addNewTabPanel = $("<li class='li-add-new-tab-panel'><a class='add-new-tab-panel' href='#blank-new-tab-panel'>+</a></li>") );
				}
			}

			$(".ui-widget-content[role='tabpanel']") //ETO PO
			// console.log($(this))
			// console.log("ul")
			// console.log($(this).find(">ul").eq(0));
			// console.log("li")
			// console.log($(this).find(">ul").eq(0).find(">.li-add-new-tab-panel").eq(0))


			$(this).find(">ul").eq(0).find(">.li-add-new-tab-panel").eq(0).on({
				"mousedown":function(e){
					tabPanelElement = $(this).closest(".tab-panel-parent-container");

					e.stopPropagation();
					addTabDialog = $('<div class="tab-panel-actions-container">'+
										'<h3><i class="icon-save"></i> Add Tab</h3><div class="hr"></div>'+
												'<div class="addTabDialog" title="Tab data">'+
													'<form>'+
														'<div class="fields">'+
															'<div class="fields"><div class="label_basic"> Title: </div><div class="input_position"><input type="text"  class="tab-title-value form-text" style="margin-top:5px;" placeholder="Title" value=""/><input type="text"  class="tab-content-value" style="display:none;margin-top:5px;" placeholder="Content" value=""/></div></div>'+
															// '<div class="label">Content</div>'+
															// '<div class="input_position2">'+
															// 	'<textarea name="tab_content" id="tab_content" class="ui-widget-content ui-corner-all input-x-medium"></textarea>'+
															// '</div>'+
														'</div>'+

														// '<div class="fields">'+
														// 	'<div class="fields">'+
														// 		'<div class="label_basic"> Visibility Formula: </div>'+
														// 		'<div class="input_position">'+
														// 			'<textarea class="form-textarea visibility-formula" style="width:100%;"></textarea>'+
														// 		'</div>'+
														// 	'</div>'+
														// '</div>'+

													'</form>'+
													'<div class="fields"><div class="label_basic"></div><div class="input_position" style="margin-top:5px;text-align:right;"><input type="button" class="btn-blueBtn add-new-tab-panel" value="Add"/>     <input type="button" class="btn-basicBtn cancel-new-tab-panel" value="Cancel" /></div></div>'+
											'</div>'+
										'</div>');

					jDialog(addTabDialog.html(), '',"500", "", "", function(){});
					// if($(".addTabDialog").find(".visibility-formula").length >= 1 ){
					// 	var title_editing = $(this).closest('li[role="tab"]').children("a.ui-tabs-anchor");
					// 	var visible_formula_tab_val = title_editing.parents("li").eq(0).attr("visible-formula");
					// 	$(".addTabDialog").find(".visibility-formula").val(visible_formula_tab_val);

					// 	$(".addTabDialog").find(".visibility-formula").on({
					// 		"keyup":function(ev){
					// 			var v_formula_value = $(this).val();
					// 			title_editing.parents("li").eq(0).attr("visible-formula",v_formula_value);
					// 			// if (typeof $(".chk_Visibility") != "undefined") {
				 //    //                 $(".chk_Visibility").find("[name='visibility-choices'][value='" + $(".getFields_" + object_id).attr("field-visible") + "']").prop("checked", true);
				 //    //                 if ($(".getFields_" + object_id).attr("field-visible") == "computed") {
				 //    //                     $(".chk_Visibility").find(".visibility-formula").val($(".getFields_" + object_id).attr("visible-formula"));
				 //    //                 }
				 //    //                 title_editing.parents("li").eq(0).attr("visible-formula",title_value);
				 //    //             }
					// 		}
					// 	})
					// }
					
					$(".add-new-tab-panel").on({
						"click":function(){
							//alert($(this).closest(".addTabDialog").find(".tab-title-value").val());
							console.log("FDJHFSI")
							console.log(tabPanelElement)
							var datass = {};
							datass.containment = settings.resizableContentContainment;
							datass.paneWidth = settings.paneWidth;
							datass.paneHeight = settings.paneHeight;
							datass.tabTitle = $(this).closest(".addTabDialog").find(".tab-title-value");
							datass.tabContent = $(this).closest(".addTabDialog").find(".tab-content-value");
							datass.tabTemplate = "<li><a href='#{href}'>#{label}</a><span class='ui-icon ui-icon-close' role='presentation' style='cursor:pointer;'>Remove Tab</span><span class='edit-title-tab-panel ui-icon ui-icon-edit' style='margin:0px;cursor:pointer;'>Edit tab</span></li>";
							datass.tabCounter = parseInt($(tabPanelElement).children(".form-tabbable-pane").attr("tabcounter"));
							datass.tabCounter++;
							$(tabPanelElement).find(">.ui-tabs").attr("tabCounter",datass.tabCounter);
							addTab($(tabPanelElement),datass);
							$("#popup_overlay").remove();
							$(this).closest("#popup_container").remove();
						}
					});
					$(".cancel-new-tab-panel").on({
						"click":function(){
							$(this).closest("#popup_container").fadeOut(500,function(){
								$(this).remove();
							});
							$("#popup_overlay").fadeOut(500,function(){
								$(this).remove();
							});
						}
					})
					e.preventDefault();
					return false;
				}
			});
			
			tabPanelElement_tabs = $(this).tabs();
			if(typeof $(this).attr("tabcounter") == "undefined"){
				$(this).attr("tabcounter",$(this).find(">.ui-tabs-nav").find(">li[role='tab']").length);
			}
			if(settings.resizableContent){
				if(settings.resizableContent == true){
					tabPanelElement_tabs.find(">.ui-widget-content[role='tabpanel']").each(function(){
						dataz = {};
						dataz.handles = 's';
						dataz.minWidth = 100;
						dataz.minHeight = 100;
						dataz.containment = settings.resizableContentContainment;
						if(settings.resizableContent == true){
							makeResizableContent($(this), dataz);
						}
					});
				}
			}
			if(settings.setContentDroppable){
				tabPanelElement_tabs.find(">.ui-widget-content[role='tabpanel']").each(function(eqi_tabPanelContent){
					dataz = {};
					dataz.accepts = settings.setContentDroppable.accepts;
					dataz.revert = settings.setContentDroppable.revert;
					dataz.greedy = settings.setContentDroppable.greedy;
					dataz.drop = settings.setContentDroppable.drop;
					makeDroppable($(this), dataz);
				});
			}
			//ui-tabs-nav
			// tabPanelElement_tabs.find(".ui-tabs-nav").css({
			//	"display":"inline-block"
			// });
			// close icon: removing the tab on click
			tabPanelElement_tabs.delegate( "span.ui-icon-close", "click", function() {
				self = $( this );
				var conf = "Are you sure you want to delete this tab?";
				jConfirm(conf, 'Confirmation Dialog','', '', '', function(r){
					if(r==true){
						var panelId = self.closest( "li" ).attr( "aria-controls" );
						self.closest(".ui-tabs").find( "#" + panelId ).remove();
						self.closest( "li" ).remove();
						tabPanelElement_tabs.tabs( "refresh" );
					}
			    });
			});
			tabPanelElement_tabs.delegate( "span.edit-title-tab-panel", "click", function() {
				// console.log("TESTINGTESTING")
				// console.log($(this));
				title_editing = $(this).closest('li[role="tab"]').children("a.ui-tabs-anchor");
				addTabDialog = $('<div class="tab-panel-actions-container">'+
									'<h3><i class="icon-save"></i> Edit Tab Title</h3><div class="hr"></div>'+
										'<div class="editTabDialog" title="Tab data">'+
											'<form>'+
												'<div class="fields">'+
													'<div class="fields">'+
														'<div class="label_basic"> Title: </div>'+
														'<div class="input_position">'+
															'<input value="'+title_editing.text()+'" type="text"  class="tab-title-value form-text" style="margin-top:5px;" placeholder="Title" value=""/>'+
															'<input type="text"  class="tab-content-value" style="display:none;margin-top:5px;" placeholder="Content" value=""/>'+
														'</div>'+
													'</div>'+
													// '<div class="label">Content</div>'+
													// '<div class="input_position2">'+
													// 	'<textarea name="tab_content" id="tab_content" class="ui-widget-content ui-corner-all input-x-medium"></textarea>'+
													// '</div>'+
												'</div>'+

												'<div class="fields">'+
													'<div class="fields">'+
														'<div class="label_basic"> Visibility Formula: </div>'+
														'<div class="input_position">'+
															'<textarea class="form-textarea visibility-formula" style="width:100%;"></textarea>'+
														'</div>'+
													'</div>'+
												'</div>'+

											'</form>'+
											'<div class="fields"><div class="label_basic"></div><div class="input_position" style="margin-top:5px;text-align:right;"><input type="button" class="btn-blueBtn edit-tab-title-panel" value="Ok"/>     <input type="button" class="btn-basicBtn cancel-new-tab-panel" value="Cancel" /></div></div>'+
										'</div>'+
									'</div>');

				jDialog(addTabDialog.html(), '',"500", "", "", function(){});
				if($(".editTabDialog").find(".visibility-formula").length >= 1 ){
					
					var visible_formula_tab_val = title_editing.parents("li").eq(0).attr("visible-formula");
					$(".editTabDialog").find(".visibility-formula").val(visible_formula_tab_val);

					$(".editTabDialog").find(".visibility-formula").on({
						"keyup":function(ev){
							var v_formula_value = ""+$(this).val();
							title_editing.parents("li").eq(0).attr("visible-formula",v_formula_value);
							title_editing.parents("li").eq(0).attr("field-visible","computed");
							// if(v_formula_value.length >= 1){
							// 	alert(132456)
							// 	title_editing.parents("li").eq(0).attr("lookup-event-trigger",true);
							// }else{
							// 	title_editing.parents("li").eq(0).attr("lookup-event-trigger",false);
							// }






							// if (typeof $(".chk_Visibility") != "undefined") {
			    //                 $(".chk_Visibility").find("[name='visibility-choices'][value='" + $(".getFields_" + object_id).attr("field-visible") + "']").prop("checked", true);
			    //                 if ($(".getFields_" + object_id).attr("field-visible") == "computed") {
			    //                     $(".chk_Visibility").find(".visibility-formula").val($(".getFields_" + object_id).attr("visible-formula"));
			    //                 }
			    //                 title_editing.parents("li").eq(0).attr("visible-formula",title_value);
			    //             }
						}
					})
				}

				$(".cancel-new-tab-panel").on({
					"click":function(){
						$(this).closest("#popup_container").remove();
						$("#popup_overlay").remove();
					}
				});

				$(".edit-tab-title-panel").on({
					"click":function(){
						title_value = $(this).closest(".editTabDialog").find(".tab-title-value").val();
						title_editing.html(title_value);
						title_editing.parents("li").eq(0).attr("name",title_value);
						$(".cancel-new-tab-panel").click();
					}
				})

			});
			tabPanelElement_tabs.bind( "keyup", function( event ) {
				if ( event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE ) {
					var panelId = tabPanelElement_tabs.find( ".ui-tabs-active" ).remove().attr( "aria-controls" );
					tabPanelElement_tabs.find( "#" + panelId ).remove();
					tabPanelElement_tabs.tabs( "refresh" );
				}
			});
		});
		function addTab(tabPanelElement, datass) {
			var label = datass.tabTitle.val() || "Tab " + datass.tabCounter,
			id = "tabs-" + datass.tabCounter+"_"+tabPanelElement.children(".form-tabbable-pane").attr("id"),
			li = $( datass.tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
			tabContentHtml = datass.tabContent.val() || ""/*"Tab " + datass.tabCounter + " content."*/;
			li.attr("name",label);

			tabPanelElement.find(">.ui-tabs").find(">.ui-tabs-nav").find(tabPanelElement.context).before( li );

			tabPanelElement.find(">.ui-tabs").append(DRThis = $("<div style='padding:0px;overflow:auto;position:relative;width:"+datass.paneWidth+";height:"+datass.paneHeight+";' id='" + id + "'><p>" + tabContentHtml + "</p></div>") );
			tabPanelElement.find(">.ui-tabs").tabs( "refresh" );

			dataz = {};
			dataz.accepts = settings.setContentDroppable.accepts;
			dataz.revert = settings.setContentDroppable.revert;
			dataz.greedy = settings.setContentDroppable.greedy;
			dataz.drop = settings.setContentDroppable.drop;
			makeDroppable($(DRThis), dataz);

			dataz = {};
			dataz.handles = 's';
			dataz.minWidth = 100;
			dataz.minHeight = 100;
			dataz.containment = datass.containment;
			if(settings.resizableContent){
				if(settings.resizableContent == true){
					makeResizableContent($(DRThis), dataz);
				}
			}
		}
		function makeDroppable(thisElement, datass){
			$(thisElement).droppable({
				accept:datass.accepts,
				revert:datass.revert,
				greedy:datass.greedy,
				drop:datass.drop
			});
		}
		function makeResizableContent(thisElement, datass){
			// console.log("make resizabvle")
			// console.log(thisElement.closest(".tabbingPanel[element-type='control']"))
			// console.log(thisElement.closest(".tabbingPanel[element-type='control']").find(">.ui-tabs-nav").eq(0));
			$(thisElement).resizable({
				handles:datass.handles,
				minWidth:datass.minWidth,
				minHeight:datass.minHeight,
				start:function(e, ui){
					parentWidths = 0;

					$(this).closest(".tabbingPanel[element-type='control']").find(">.ui-tabs-nav").eq(0).find(">li").each(function(){
						parentWidths = parentWidths + $(this).width();
					});
					
					$(ui.helper).resizable("option","minWidth",parentWidths);
				},
				resize:function(e, ui){
					containment = datass.containment;
					//droppable_offset_top = $(containment).offset().top
					//droppable_offset_left = $(containment).offset().left
					if($(containment).length >= 1){
						droppable_width = $(containment).width();
						droppable_height = $(containment).height();

						this_ele_top = $(this).closest(".setObject").position().top;
						this_ele_left = $(this).closest(".setObject").position().left;

						this_ele_bottom = $(this).closest(".setObject").position().top + $(this).closest(".setObject").height();
						this_ele_right = $(this).closest(".setObject").position().left + $(this).closest(".setObject").width();
						console.log(this_ele_bottom+" >= "+droppable_height);
						if(	this_ele_bottom >= droppable_height ){
							$(this).css({
								height: ($(this).height() - Math.abs(this_ele_bottom-droppable_height))+"px"
							});
							// $(this).closest(".element").find(".blockings").css({
							// 	height: ($(this).closest(".element").find(".blockings").height() - Math.abs(this_ele_bottom-droppable_height))+"px"
							// });
							//refreshBlockings($(ui.helper));
						}
					}
				}
			});
		}
	}
}(jQuery));